﻿using HardwareWebApi.Controllers;
using HardwareWebApi.Util;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace HardwareWebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            /**
             * 处理跨域
             */
            services.AddCors(options =>
            {   
                // 配置跨域处理
                options.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin() // 允许任何来源的主机
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();     // 制定处理cookie
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(WebApiResultMiddleware));
                options.RespectBrowserAcceptHeader = true;
            });

            //var config = Configuration.GetConnectionString("ConnString");

            //var connectstring = configuration.getconnectionstring("connstring");
            //services.adddbcontext<conn>(options => options.usemysql(connectstring));

            //console.write("connstring from start up>> " + connectstring + "\n");

            services.AddOptions();

            SqlConfigUtil.config(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            //app.UseHttpsRedirection();
            //app.UseCors("any");

            // 使用中间件 记录访问IP
            logger.AddConsole(minLevel: LogLevel.Information);
            app.UserRequestIP(); // 使用中间件
            // 
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello world!");
            //});
            app.UseOutImg();

            app.UseMvc();
        }
    }
}
